package com.jltx.xq.simplewatch.video.ui;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.jltx.xq.simplewatch.R;
import com.jltx.xq.simplewatch.base.BaseSupportFragment;
import com.jltx.xq.simplewatch.news.model.bean.TopicNewTipEntity;
import com.jltx.xq.simplewatch.news.model.bean.TopicNews;
import com.jltx.xq.simplewatch.utils.ListUtils;
import com.jltx.xq.simplewatch.utils.NetWorkUtil;
import com.jltx.xq.simplewatch.utils.NewsStateUtils;
import com.jltx.xq.simplewatch.video.adapter.TopicNewsAdapter;
import com.jltx.xq.simplewatch.video.presenter.ITopicNewsPresenter;
import com.jltx.xq.simplewatch.video.presenter.impl.TopicNewsPresenterImpl;
import com.jltx.xq.simplewatch.video.view.ITopicNewsView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.jltx.utils.XqLog;
import cn.jltx.utils.XqToast;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerManager;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;

import static fm.jiecao.jcvideoplayer_lib.JCVideoPlayer.CURRENT_STATE_PLAYING;

/**
 * @author jltxseo
 *         Created by junlintianxia on 2017/09/06.
 */

public class VideoNewsListFragment extends BaseSupportFragment<ITopicNewsPresenter> implements ITopicNewsView,SwipeRefreshLayout.OnRefreshListener,BaseQuickAdapter.RequestLoadMoreListener,BaseQuickAdapter.OnItemClickListener,BaseQuickAdapter.OnItemChildClickListener,TopicNewsAdapter.OnVideoClickToStartListener{
    private static final String TAG = "MyVideoNewsListFragment";
    private static final String CHANNEL_CODE_PARAM = "channel_code_prams";
    private static final String CHANNEL_TITLE_PARAM = "channel_title_prams";

    @BindView(R.id.swipe_refresh_frg_video_list)
    SwipeRefreshLayout swipeRefreshLayout;

    @BindView(R.id.recyclerview_frg_video_list)
    RecyclerView recyclerView;

    View emptyView;

    private String channelTitle;
    private String channel;
    private TopicNewsAdapter topicNewsAdapter;
    private List<TopicNews> newsList = new ArrayList<>();


    public static VideoNewsListFragment newInstance(String title,String channel){
        VideoNewsListFragment fragment = new VideoNewsListFragment();
        Bundle bundle = new Bundle();
        bundle.putString(CHANNEL_TITLE_PARAM,title);
        bundle.putString(CHANNEL_CODE_PARAM,channel);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_video_list_act;
    }

    @Override
    public ITopicNewsPresenter initPresenter() {
        return new TopicNewsPresenterImpl(this);
    }

    @Override
    public void initView(View rootView, Bundle savedInstanceState) {
        channelTitle = getArguments().getString(CHANNEL_TITLE_PARAM);
        channel = getArguments().getString(CHANNEL_CODE_PARAM);
        setSwipeRefreshLayoutColor(swipeRefreshLayout);
        recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        recyclerView.setHasFixedSize(true);
        recyclerView.addOnScrollListener(onScrollListener);
        emptyView = getActivity().getLayoutInflater().inflate(R.layout.page_net_error,(ViewGroup)recyclerView.getParent(),false);
        emptyView.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                onRefresh();
            }
        });
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {  //Fragment延时加载
        super.onLazyInitView(savedInstanceState);
        topicNewsAdapter = new TopicNewsAdapter(newsList,false,true);
        topicNewsAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        topicNewsAdapter.setEnableLoadMore(true);
        topicNewsAdapter.setOnLoadMoreListener(this,recyclerView);
        topicNewsAdapter.setOnItemClickListener(this);
        topicNewsAdapter.setOnItemChildClickListener(this);
        topicNewsAdapter.setOnVideoClickToStartListener(this);
        swipeRefreshLayout.setOnRefreshListener(this);
        recyclerView.setAdapter(topicNewsAdapter);
        XqLog.d(TAG,"onLazyInitView");
        presenter.getTopicNews(channel,true);
    }

    @Override
    public void onUserVisible() { //再次回来界面显示时调用
        if(((TopicNewsPresenterImpl)presenter).getIsLoading().get() == false && ListUtils.isEmpty(newsList)){
            XqLog.d(TAG,"onUserVisible");
            presenter.getTopicNews(channel,true);
        }
        super.onUserVisible();
    }

    //下拉回调
    @Override
    public void onRefresh() {
        //下拉获取网络数据
        presenter.getTopicNews(channel,true);
    }

    //上拉回调
    @Override
    public void onLoadMoreRequested() {
        if (presenter.getLastNewsRecordPage() == 0 || presenter.getLastNewsRecordPage() == 1) {
            //如果记录的页数为0(即是创建的空记录)，或者页数为1(即已经是第一条记录了)
            //mRefreshLayout.endLoadingMore();//结束加载更多
            topicNewsAdapter.loadMoreEnd();
            return;
        }
        //下拉获取网络数据
        presenter.getTopicNews(channel,false);
    }

    private RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            if (JCVideoPlayerManager.getCurrentJcvd() != null) {
                JCVideoPlayerStandard videoPlayer = (JCVideoPlayerStandard) JCVideoPlayerManager.getCurrentJcvd();
                if (videoPlayer.currentState == CURRENT_STATE_PLAYING) {
                    //如果正在播放
                    LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                    int firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition();
                    int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();

                    if (firstVisibleItemPosition > videoPlayer.getPosition() || lastVisibleItemPosition < videoPlayer.getPosition()) {
                        //如果第一个可见的条目位置大于当前播放videoPlayer的位置
                        //或最后一个可见的条目位置小于当前播放videoPlayer的位置，释放资源
                        JCVideoPlayer.releaseAllVideos();
                    }
                }
            }
        }
    };

    /**
     * ItemView里面的子View点击事件
     * @param adapter
     * @param view     The view whihin the ItemView that was clicked
     * @param position The position of the view int the adapter
     */
    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()){
            case R.id.iv_avatar:
                XqToast.showToastShortMsg(getActivity(),"点击头像");
                break;
            case R.id.tv_focus:
                XqToast.showToastShortMsg(getActivity(),"点击关注");
                break;
            case R.id.img_more:
                XqToast.showToastShortMsg(getActivity(),"点击更多");
                break;
        }
    }

    /**
     * ItemView点击事件
     * @param adapter  the adpater
     * @param view     The itemView within the RecyclerView that was clicked (this
     *                 will be a view provided by the adapter)
     * @param position The position of the view in the adapter.
     */
    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        TopicNews topicNews = (TopicNews)adapter.getItem(position);
        if(topicNews != null && topicNews.getIsRead() == 0){ //点击自动标记已读
            presenter.updateNewsState(channel,NewsStateUtils.convertTopicNewsStateKey(topicNews),1,topicNews.getIsDel(),position);
        }
    }

    @Override
    public void onVideoClickToStar(BaseViewHolder helper, TopicNews topicNews,JCVideoPlayerStandard videoPlayer) {
        if(!NetWorkUtil.isNetWorkAvailable(mActivity)){ //点击播放视频时判断一下网络是否可用
            swipeRefreshLayout.setRefreshing(false);
            XqToast.showToastShortMsg(mActivity,getString(R.string.net_error_tip));
            return;
        }
        XqToast.showToastShortMsg(getActivity(),"开始播放视频");
        helper.setVisible(R.id.ll_duration,false); //隐藏时长
        helper.setVisible(R.id.ll_title,false); //隐藏文字标题栏
        final String srcUrl = topicNews.getUrl();
        final String title = topicNews.getTitle();
        final int pos = helper.getAdapterPosition();
        prePareVideoPath(srcUrl,title,pos);
    }

    @Override
    public void showError(String msg) {
        XqLog.d(TAG,"showError");
    }

    @Override
    public void onGetNewsListSuccess(List<TopicNews> topicNewsList, TopicNewTipEntity tips, boolean isDown) {
        if(!ListUtils.isEmpty(topicNewsList)){
            XqLog.d(TAG,"--------------------onGetNewsListSuccess");
            for (TopicNews topicNews : topicNewsList){
                XqLog.d(TAG,"title=>"+topicNews.getTitle());
            }
            XqLog.d(TAG,"onGetNewsListSuccess--------------------");
            JCVideoPlayer.releaseAllVideos();
            if(isDown){
                XqLog.d(TAG,"下拉数据成功刷新界面");
                topicNewsAdapter.addData(0,topicNewsList); //添加到集合头部，并刷新数据
                topicNewsAdapter.notifyDataSetChanged();
            }else {
                XqLog.d(TAG,"上拉数据成功刷新界面");
                topicNewsAdapter.addData(topicNewsList);//添加到集合下面，刷新adapter
            }
        }

        if(ListUtils.isEmpty(newsList)){
            topicNewsAdapter.setEmptyView(emptyView);
        }
    }

    @Override
    public void showLoadingView(boolean isDown) {
        XqLog.d(TAG,"showLoadingView");
        if(isDown && !NetWorkUtil.isNetWorkAvailable(mActivity)){ //下拉等待时先判断一下当前的网络是否可用，不可用就停止下拉并显示网络不同的提示
            swipeRefreshLayout.setRefreshing(false);
            XqToast.showToastShortMsg(mActivity,getString(R.string.net_error_tip));
            return;
        }
        //当当前新闻列表为空时自动显示正在加载的等待动画
        topicNewsAdapter.setEmptyView(R.layout.loading_flash_view, (ViewGroup) recyclerView.getParent());
    }

    @Override
    public void hideLoadingView(boolean isDown) {
        XqLog.d(TAG,"hideLoadingView");
        if(isDown){
            XqLog.d(TAG,"停止下拉数据");
            swipeRefreshLayout.setRefreshing(false);
        }else {
            XqLog.d(TAG,"停止上拉数据");
            topicNewsAdapter.loadMoreComplete();
        }
        if(ListUtils.isEmpty(newsList)){ //当当前新闻列表为空时显示空白页
            topicNewsAdapter.setEmptyView(emptyView);
        }
    }

    public void prePareVideoPath(String srcUrl, String title, int position){
        presenter.getTopicNewsVideoPath(srcUrl,title,position);
    }
    @Override
    public void onGetNewsVideoPathSuccess(String videoUrl, String srcUrl, String title, int position) {
        TopicNews topicNews = topicNewsAdapter.getItem(position);
        if(topicNews != null && topicNews.getUrl().equals(srcUrl) && topicNews.getTitle().equals(title)){
            View playerView = topicNewsAdapter.getViewByPosition(position,R.id.video_player);
            if(playerView instanceof JCVideoPlayerStandard){
                JCVideoPlayerStandard videoPlayer = (JCVideoPlayerStandard)playerView;
                if(videoPlayer.getPosition() == position){
                    videoPlayer.setUp(videoUrl, JCVideoPlayer.SCREEN_LAYOUT_LIST,topicNews.getTitle());
                    videoPlayer.seekToInAdvance = topicNews.getVideo_detail_info().progress;
                    videoPlayer.startVideo();
                }
            }
        }
    }


    @Override
    public void onGetNewsVideoPathRetry(String srcUrl, String title, int position) {
        prePareVideoPath(srcUrl,title,position);
    }

    @Override
    public void onGetNewsVideoPathErro(String srcUrl, String title, int position) {
        XqToast.showToastShortMsg(mActivity,"获取视频链接失败，请重试!");
        TopicNews topicNews = topicNewsAdapter.getItem(position);
        if(topicNews != null && topicNews.getUrl().equals(srcUrl) && topicNews.getTitle().equals(title)){
            View llDuration = topicNewsAdapter.getViewByPosition(position,R.id.ll_duration);
            if(llDuration != null)llDuration.setVisibility(View.VISIBLE);
            View llTitle = topicNewsAdapter.getViewByPosition(position,R.id.ll_title);
            if(llTitle != null)llTitle.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onUpdateNewsStateSuccess(String channel, String key, int isRead, int isDel, int position) {
        TopicNews topicNews = topicNewsAdapter.getItem(position);
        XqLog.d(TAG,"onUpdateNewsStateSuccess第"+position+"个item");
        if(topicNews != null && NewsStateUtils.convertTopicNewsStateKey(topicNews).equals(key)){
            if(isDel != 0){
                topicNews.setIsRead(isRead);
                topicNews.setIsDel(isDel);
                topicNewsAdapter.remove(position);
            }else {
                XqLog.d(TAG,"第"+position+"个item标记已读");
                topicNews.setIsRead(isRead);
                topicNews.setIsDel(isDel);
                topicNewsAdapter.setData(position,topicNews);
            }
        }
    }

    @Override
    public void onUpdateNewsStateFail(String channel, String key, int isRead, int isDel, int position) {

    }
}
